package com.example.web.controller;

import com.example.web.entity.LoginRequest;
import com.example.web.entity.LoginResponse;
import com.example.web.entity.Result;
import com.example.web.entity.User;
import com.example.web.service.MenuService;
import com.example.web.service.UserService;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class AuthController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private MenuService menuService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = userService.login(loginRequest);
            return Result.success("登录成功", response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/userinfo")
    public Result<User> getUserInfo(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未提供认证信息");
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            if (!jwtUtils.validateToken(token, username)) {
                return Result.error(401, "认证信息无效");
            }
            
            User user = userService.findByUsername(username);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            
            // 不返回密码
            user.setPassword(null);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error(401, "认证失败");
        }
    }

    /**
     * 获取用户权限
     */
    @GetMapping("/permissions")
    public Result<List<String>> getUserPermissions(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未提供认证信息");
            }
            
            String username = jwtUtils.getUsernameFromToken(token);
            if (!jwtUtils.validateToken(token, username)) {
                return Result.error(401, "认证信息无效");
            }
            
            User user = userService.findByUsername(username);
            if (user == null) {
                return Result.error(404, "用户不存在");
            }
            
            // 获取用户权限
            List<String> permissions = menuService.getPermissionsByUserId(user.getId());
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error(401, "获取权限失败");
        }
    }
    
    /**
     * 登出（前端处理，删除token）
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("登出成功", null);
    }

    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}